/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.tchepannou.limbe.impl;

import com.tchepannou.limbe.Controller;
import com.tchepannou.limbe.I18n;
import com.tchepannou.limbe.Service;
import com.tchepannou.limbe.engine.Engine;
import com.tchepannou.limbe.helper.MethodInvoker;

import javax.mail.MessagingException;
import java.io.IOException;
import java.io.Serializable;
import java.util.Locale;


/**
 * Abstract implementation of {@link Controller}
 * @author herve
 */
public abstract class AbstractController
    implements Controller
{
    //-- Attribute
    private I18n __i18n;
    
    //-- Public
    public MethodInvoker getMethodInvoker (String path, Serializable data)
    {
        Object[] records = data != null ? new Object[] {data} : null;
        String methodName = getMethodName (path);
        return methodName != null
            ? new MethodInvoker (methodName, this, records)
            : null;
    }

    protected String getMethodName (String path)
    {
        /* Extract the last part of the path */
        String xpath = path.startsWith ("/") ? path.substring (1) : path;
        int i = xpath.lastIndexOf ("/");
        String name = i > 0 ? xpath.substring (i + 1) : null;

        /* remove extension */
        int j = name.indexOf (".");
        return j > 0 ? name.substring (0, j) : name;
    }

    public I18n getI18n ()
    {
        if (__i18n == null)
        {
            __i18n = new I18n (getBundleName (), getLocale ());
        }
        return __i18n;
    }
    
    public String getBundleName ()
    {
        return I18n.DEFAULT_BUNDLE_NAME;
    }
    
    public Locale getLocale ()
    {
        return Locale.getDefault ();
    }
    
    //-- Protected
    /**
     * Deliver an email
     *
     * @see ContainerContext#deliver(java.lang.String, java.io.Serializable)
     */
    protected final void deliver (String action, Serializable data)
        throws IOException,
               MessagingException
    {
        Engine.getInstance ().getMailContainer ().deliver (action, data);
    }

//    /**
//     * Send a message to a MessageController
//     *
//     * @see ContainerContext#sendMessage(java.lang.String, java.io.Serializable)
//     */
//    protected final void sendMessage (String destination)
//        throws JMSException
//    {
//        sendMessage (destination, null);
//    }
//
//    /**
//     * @see ContainerContext#sendMessage(java.lang.String, java.io.Serializable)
//     */
//    protected final void sendMessage (String destination, Serializable message)
//        throws JMSException
//    {
//        getContext ().getContainerContext ().sendMessage (destination, message);
//    }


    protected final <T extends Service> T findService (Class<T> type)
    {
        return getContext ().findService (type);
    }

}
